package com.ibm.ecm.configmgr.app.acm.widgets.rest;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;


import org.apache.commons.codec.binary.Base64;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HttpContext;

import com.ibm.ecm.configmgr.app.acm.widgets.util.XMLUtils;

public class RESTUtil {
	String hostname = "localhost";
	String port = "9443";
	String username = "administrator";
	String password = "filenet";
	DefaultHttpClient client = null;
	String loginURL="";
	private static String packageName = RESTUtil.class.getPackage().getName();

	public static RESTUtil getJSONUtil(Properties props)
			throws IllegalAccessException, InstantiationException,
			ClassNotFoundException {
		// Use reflect to initialize concrete RepresentationManager
		// instance
		String className = packageName + "." + "RESTUtilOnJSON";
		RESTUtil util = (RESTUtil) Class.forName(className).newInstance();
		util.init(props);
		return util;
	}

	public static RESTUtil getATOMUtil(Properties props)
			throws IllegalAccessException, InstantiationException,
			ClassNotFoundException {
		// Use reflect to initialize concrete RepresentationManager
		// instance
		String className = packageName + "." + "RESTUtilOnATOM";
		RESTUtil util = (RESTUtil) Class.forName(className).newInstance();
		util.init(props);
		return util;
	}
	

	public void setLoginUrl(String url){
		loginURL = url;
	}
	
	public void init(Properties props){
		this.setHostname(props.getProperty("HOSTNAME").toString());
		this.setPort(props.getProperty("PORT").toString());
		this.setUsername(props.getProperty("USERNAME").toString());
		this.setPassword(props.getProperty("PASSWORD").toString());
		loginURL = "http://"+getHostname()+":"+getPort()+"/mum/enabler";
		
		
		BasicHttpParams params = new BasicHttpParams();
		params.setParameter("http.protocol.allow-circular-redirects", Boolean.TRUE);
		ConnManagerParams.setMaxTotalConnections(params, 100);

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Integer.parseInt(this.getPort())));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        
		this.client = new DefaultHttpClient();
//		RESTReuseStrategy rs = new RESTReuseStrategy();
//		this.client.setReuseStrategy(rs); 
//        this.client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
		this.client.getCredentialsProvider().setCredentials(
				new AuthScope(this.getHostname(), Integer.parseInt(this.getPort()),AuthScope.ANY_REALM),
				new UsernamePasswordCredentials(this.getUsername(), this.getPassword()));

		
	        Map<String, String> cookies;
			try {
				cookies = MashupMakerProxy.loginMashupMaker(loginURL,getUsername(),getPassword());

	        
//	        Protocol mashupHttps = new Protocol("https", new MashupSSLProtocolSocketFactory(), Integer.parseInt(getPort()));
//	        Protocol.registerProtocol("https", mashupHttps);

			params.setParameter("LtpaToken2", cookies.get("LtpaToken2").toString());
			params.setParameter("LtpaToken", cookies.get("LtpaToken2").toString());
			params.setParameter("JSESSIONID", cookies.get("JSESSIONID").toString());
	        //connection timeout 50 sec
			HttpConnectionParams.setSoTimeout(params, 50000);
			this.client.setParams(params);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
	}
	public String uploadTemplate(String url, String filename) throws Exception{
		HttpResponse response =null;
		String boundary = "--" + this.getBoundaryString();


			String contentType = "multipart/form-data;boundary=" + this.getBoundaryString();
	
			HttpPost postMethod = new HttpPost(url);
			//postMethod.setDoAuthentication(true);

			postMethod.addHeader("content-type", contentType);
			String cred = this.getUsername() + ":" + this.getPassword();
			String authHeader = "Basic "+ new String(Base64.encodeBase64(cred.getBytes()));
			postMethod.addHeader("Authorization", authHeader);

			ByteArrayOutputStream body = fillStream(filename);
			ByteArrayEntity requestEntity = new ByteArrayEntity(body.toByteArray());
			
	        
	        postMethod.setEntity(requestEntity);
	        String templateString="";
	        String templateID=null;
			try{
	        response =this.client.execute(postMethod);

			System.out.println("Status code: " + response.getStatusLine().getStatusCode());
			System.out.println("Status Text: " + response.getStatusLine().getReasonPhrase());
			HttpEntity resEntity = response.getEntity();
			InputStream responseBody = resEntity.getContent();
			XMLUtils util = new XMLUtils(responseBody);
			templateString = util.getNodeValue("/atom:feed/atom:entry/atom:id");
			String[] id = templateString.split(":");
			if(id.length==3){
				templateID = id[2];
			}
		}catch (IOException e){
			e.printStackTrace();
		}

		return templateID;
	}
	
	private ByteArrayOutputStream fillStream(String filename) throws IOException {

		ByteArrayOutputStream body = new ByteArrayOutputStream();
		File file = new File(filename);
		FileInputStream fileInput = new FileInputStream(file);
		
		String boundary = "--" + this.getBoundaryString();
		// write file
		body.write(boundary.getBytes());
		body.write("\r\n".getBytes());
		body.write(("Content-Disposition: form-data; name=\"zip\"; filename=\""+filename+"\"").getBytes());
		body.write("\r\n".getBytes());
		body.write("Content-Type: application/zip".getBytes());
		body.write("\r\n".getBytes());
		body.write("\r\n".getBytes());

		byte[] buf = new byte[4096];
		int len = 0;
		while ((len = fileInput.read(buf)) != -1) {
			body.write(buf, 0, len);
		}
		body.write("\r\n".getBytes());

		body.write((boundary + "--").getBytes());
		return body;
	}
	
	public String getBoundaryString() {
		return "------------------------10102754414578508781458777923--";
	}
	public void closeConnection(){
		this.client=null;
	}
	public void setHostname(String hostname){
		this.hostname=hostname;
	}
	public String getHostname(){
		return this.hostname;
	}
	
	public void setPort(String port){
		this.port=port;
	}
	public String getPort(){
		return this.port;
	}
	
	public void setUsername(String username){
		this.username=username;
	}
	public String getUsername(){
		return this.username;
	}
	
	public void setPassword(String password){
		this.password=password;
	}
	
	public String getPassword(){
		return this.password;
	}
	
	protected String getResponseInString(InputStream in) {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		try {
			for (int n; (n = in.read(b)) != -1;) {
				out.append(new String(b, 0, n));
			}
		} catch (IOException e) {
			//TODO: Error handling
		}
		return out.toString();
	}
}
